import time
from threading import Thread

from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QImage, QPixmap


# pickle QPixmap

class ThreadOpencvToQpixmap(Thread):
    def __init__(self, my_thread_queue_image_done, my_process_queue_image_processed, my_end):
        super(ThreadOpencvToQpixmap, self).__init__()

        self.my_thread_queue_image_done = my_thread_queue_image_done
        self.my_process_queue_image_processed = my_process_queue_image_processed
        self.my_end = my_end

        self.is_running = True
        self.w = 960
        self.h = 540

    def run(self) -> None:
        time.sleep(0.5)
        while self.is_running:
            flag = self.function()
            if not flag:
                time.sleep(0.0015)

    def stop(self):
        self.is_running = False

    def function(self):
        if self.my_process_queue_image_processed.empty():
            if not self.my_end.empty():
                self.is_running = False
            return False
        else:
            frame, image, data = self.my_process_queue_image_processed.get()
            size = QSize(self.w, self.h)
            image = QImage(image.data.tobytes(), image.shape[1], image.shape[0], image.shape[1] * 3,
                           QImage.Format_RGB888)
            image = QPixmap.fromImage(image.scaled(size, Qt.IgnoreAspectRatio))
            self.my_thread_queue_image_done.put([frame, image, data])
            return True
